import { MODEL_NAME } from '../../constants/model-names';
import { EVENTS, type IEventBus } from '../../events';
import type {
  OfflineEarningsModel,
  RealmModel,
  SectModel,
  WalletModel,
} from '../../model';
import { CURRENCY_TYPE } from '../../model/wallet';
import { BaseSystem } from '../base';
import type { PlayerStateSystem } from '../player-state';

export class OfflineEarningsSystem extends BaseSystem {
  private bus: IEventBus;
  private playerStateSystem: PlayerStateSystem;

  constructor(bus: IEventBus, playerStateSystem: PlayerStateSystem) {
    super();
    this.bus = bus;
    this.playerStateSystem = playerStateSystem;

    this.bus.on(EVENTS.OFFLINE_EARNINGS_SET_OFFLINE_TIME, (time: number) => {
      const offlineEarningsModel =
        this.playerStateSystem.getModel<OfflineEarningsModel>(
          MODEL_NAME.OFFLINE_EARNINGS
        );
      if (!offlineEarningsModel) return;
      offlineEarningsModel.setOfflineTime(time);
    });

    this.bus.on(EVENTS.OFFLINE_EARNINGS_GET_EARNINGS, () => {
      const offlineEarningsModel =
        this.playerStateSystem.getModel<OfflineEarningsModel>(
          MODEL_NAME.OFFLINE_EARNINGS
        );
      const realmModel = this.playerStateSystem.getModel<RealmModel>(
        MODEL_NAME.REALM
      );
      const sectModel = this.playerStateSystem.getModel<SectModel>(
        MODEL_NAME.SECT
      );
      const walletModel = this.playerStateSystem.getModel<WalletModel>(
        MODEL_NAME.WALLET
      );
      if (!offlineEarningsModel || !realmModel || !sectModel || !walletModel)
        return;
      const earnings = offlineEarningsModel.getEarnings();
      const realmInfo = offlineEarningsModel.getRealmInfo();
      realmModel.addExp(earnings.realm.value);
      sectModel.addSectContribution(earnings.sectContribution.value);
      sectModel.setSectCultivationSpotValidCount(
        realmInfo.sectCultivationSpotValidCount
      );
      walletModel.addCurrency(
        CURRENCY_TYPE.SPIRIT_STONE,
        earnings.spiritualStone.value
      );
      offlineEarningsModel.resetEarnings();
      this.bus.emit(EVENTS.OFFLINE_EARNINGS_GET_EARNINGS_SUCCESS);
    });
  }
}
